package com.donde.coche;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

import java.io.IOException;
import java.util.List;
import java.util.Locale;


public class VerPosicion extends MapActivity {

	MapView mapview;
	MapController mc;
	GeoPoint p;
	
	LocationManager lm;
	LocationListener locationListener;
	
	
	private class MapOverlay extends com.google.android.maps.Overlay{
		@Override
		public boolean draw (Canvas canvas, MapView mapView, boolean shadow, long when){
			super.draw(canvas, mapView, shadow);
			
			//Traducir GeoPoint en p�xeles de pantalla
			Point screenPts = new Point();
			mapView.getProjection().toPixels(p, screenPts);
			
			//A�adir el marcador
			Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.chincheta);
			canvas.drawBitmap(bmp, screenPts.x, screenPts.y-10, null); 
			return true;
		}
	/*
		@Override
		public boolean onTouchEvent(MotionEvent event, MapView mapView){
			//Cuando el usuario levanta el dedo...
			if(event.getAction() == 1){
				GeoPoint p = mapView.getProjection().fromPixels((int) event.getX(), (int) event.getY());
				
				Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
				try{
					List<Address> addresses = geoCoder.getFromLocation(p.getLatitudeE6()/ 1E6, p.getLongitudeE6() / 1E6, 1);
					String add = "";
					if(addresses.size() > 0){
						for( int i=0; i < addresses.get(0).getMaxAddressLineIndex(); i++){
							add += addresses.get(0).getAddressLine(i) + "\n";
						}
						Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
					}
				}catch (IOException e){
					e.printStackTrace();
				}
				return true;
			}
			return false;
			
		}*/
	}
	
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ver_posicion);
        
        mapview = (MapView) findViewById(R.id.mapView);
        mapview.setBuiltInZoomControls(true);
        mapview.setSatellite(true);
        mapview.setTraffic(true);
        
        
        mc = mapview.getController();
        /*String coordinates[] = {"43.370873","-8.395835"};
        double lat = Double.parseDouble(coordinates[0]);
        double lng = Double.parseDouble(coordinates[1]);
        
        p = new GeoPoint(
        		(int) (lat * 1E6),
        		(int) (lng * 1E6));
        
        mc.animateTo(p);
        mc.setZoom(13);
        
        */
        /*
        
        //A�adir un marcador
        MapOverlay mapOverlay = new MapOverlay();
        List<Overlay> listOfOverlays = mapview.getOverlays();
        listOfOverlays.clear();
        listOfOverlays.add(mapOverlay);
        
        mapview.invalidate();  //Dice al mapa que tiene algo nuevo que pintar.
          */	
        
		Toast.makeText(getBaseContext(), "Conectando con el GPS \n Espere hasta ver su posici�n" , Toast.LENGTH_SHORT).show();

        
        //Utilizar la clase LocationManager para obtener datos de ubicaci�n
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        
        locationListener = new MyLocationListener();
    }
    
    @Override
    public void onResume(){
    	super.onResume();
    	if(lm != null){
    		//Actualizamos la posici�n
    		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
    	}
    }
    
    @Override
    public void onPause(){
    	super.onPause();
    	if(lm != null){
    		//Eliminamos el oyente de ubicaci�n
    		lm.removeUpdates(locationListener);
    	}
    }
    
    private class MyLocationListener implements LocationListener{
    	
    	public void onLocationChanged(Location loc){
    		if(loc != null && lm != null){
    			//Toast.makeText(getBaseContext(), "Posici�n Guardada: Lat: "+loc.getLatitude()+" Long: "+loc.getLongitude() , Toast.LENGTH_SHORT).show();
    			
    			p = new GeoPoint ((int) (loc.getLatitude()* 1E6),
    							  (int) (loc.getLongitude()* 1E6));
    			
    			direccion(p);
    			Compartir c = new Compartir(loc.getLatitude(),loc.getLongitude());
    			
    			mc.animateTo(p);
    			mc.setZoom(18);
    			
    			//A�adir un marcador
    	        MapOverlay mapOverlay = new MapOverlay();
    	        List<Overlay> listOfOverlays = mapview.getOverlays();
    	        listOfOverlays.clear();
    	        listOfOverlays.add(mapOverlay);
    	        
    	        mapview.invalidate();  //Dice al mapa que tiene algo nuevo que pintar.
    	        
    	        //#TODO
    	        
    	        
    	        c.escribirContenido();
    	        
    	        lm.removeUpdates(locationListener);
    	        lm = null;
    		}
    	}
    	
		public void direccion (GeoPoint p){
						
			Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
			try{
				List<Address> addresses = geoCoder.getFromLocation(p.getLatitudeE6()/ 1E6, p.getLongitudeE6() / 1E6, 1);
				String add = "";
				if(addresses.size() > 0){
					for( int i=0; i < addresses.get(0).getMaxAddressLineIndex(); i++){
						add += addresses.get(0).getAddressLine(i) + "\n";
					}
					Toast.makeText(getBaseContext(), add, Toast.LENGTH_LONG).show();
				}
			}catch (IOException e){
				e.printStackTrace();
			}
    }
    	public void onProviderDisabled(String provider){	}
    	public void onProviderEnabled(String provider){}
    	public void onStatusChanged(String provider, int status, Bundle extras){}
    }

    /*@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_ver_posicion, menu);
        return true;
    }

    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }*/
    
    @Override
    protected boolean isRouteDisplayed() {
    	//TODO Auto-generated method sub
    	return false;
    }

}
